let global_page = 1,
  global_limit = 5,
  orderUrl = '/order';

function loadOrder(no) {
  loadLayuiForm();
  no = no === 'undefined' ? '' : no;
  $.get(orderUrl + '/findAllOrdersByPage', {page: global_page, limit: global_limit, no: no}, orders => {
    if (orders.data.length === 0 && global_page > 1) {
      global_page--;
      loadOrder();
    } else {
      loadOrders(orders);
      loadOrderLayPage(orders);
    }
  });
}

function loadOrders(orders) {
  layui.use(['table', 'layer'], () => {
    let table = layui.table,
      layer = layui.layer;
    table.render({
      elem: '#order',
      data: orders.data,
      toolbar: '#order-toolbar',
      cols: [
        [
          {field: 'no', title: '订单编号', width: 300},
          {field: 'goods', title: '商品名称'},
          {field: 'count', title: '数量'},
          {
            field: 'mumlti', title: '总价/元', templet: data => {
              return '￥' + data.multi;
            }
          },
          {field: 'ctime', title: '订单创建时间', width: 250},
          {
            field: 'status', title: '订单状态', templet: data => {
              let status = '';
              switch (data.status) {
                case 1:
                  status = '订单提交成功，结算中';
                  break;
                case 2:
                  status = '结算成功';
                  break;
                case 3:
                  status = '订单完成';
              }
              return status;
            }
          },
          {title: '操作', toolbar: '#order-tool'}
        ]
      ]
    });
    table.on('toolbar(order)', elem => {
      switch (elem.event) {
        case 'add':
          $('#add-order-layout input[name=creater]').val($('.layui-header .layui-nav-item a:eq(0)').text());
          showLayout($('#add-order-layout'));
          break;
        case 'search':
          loadOrder($('#search').val());
          break;
      }
    });
    table.on('tool(order)', elem => {
      let event = elem.event,
        data = elem.data;
      switch (event) {
        case 'detail':
          $.get(orderUrl + '/findById/' + data.id, order => {
            $('#detail-order-layout .layout-title span').html(order.no);
            let elem = $('#detail-order-layout').find('input'),
              status = order.status === 1 ? '订单提交成功，结算中' : (order.status === 2 ? '结算成功' : '订单完成');
            $.each(elem, (i) => {
              elem.eq(i).val(order[elem.eq(i).attr('name')]);
            });
            $('#detail-order-layout input[name=status]').val(status);
          });
          showLayout($('#detail-order-layout'));
          break;
        case 'edit':
          $.get(orderUrl + '/findById/' + data.id, order => {
            $('#edit-order-layout .layout-title span').html(order.no);
            let elem = $('#edit-order-layout').find('input');
            $.each(elem, (i) => {
              elem.eq(i).val(order[elem.eq(i).attr('name')]);
            });
            $('#edit-order-layout select option').eq(order.status - 1).prop('selected', true);
            resetForm();
          });
          showLayout($('#edit-order-layout'));
          break;
      }
    });
  });
}

function loadOrderLayPage(orders) {
  layui.use('laypage', () => {
    layui.laypage.render({
      elem: 'order-page',
      limit: global_limit,
      limits: [5, 10, 20, 50],
      count: orders.count,
      layout: ['count', 'prev', 'page', 'next', 'limit'],
      jump: function (obj, first) {
        if (!first) {
          global_page = obj.curr;
          global_limit = obj.limit;
          loadOrder();
        }
      }
    });
  })
}

function loadLayuiForm() {
  layui.use(['element', 'form', 'layer'], () => {
    let form = layui.form,
      layer = layui.layer;
    form.on('submit(add)', elem => {
      let field = elem.field;
      if (!/^\d+$/ig.test(field.count)) {
        layer.msg('数量必须为整数!');
      } else {
        $.post(orderUrl + '/addOrder', field, result => {
          result = result > 0 ? '成功' : '失败';
          layer.msg('订单提交' + result + '!');
          hideLayout($('#add-order-layout'));
          loadOrder();
        });
      }
    });
    form.on('submit(edit)', elem => {
      let field = elem.field;
      if (!/^\d+$/ig.test(field.count)) {
        layer.msg('数量必须为整数!');
      } else {
        $.post(orderUrl + '/updateOrder', field, result => {
          result = result > 0 ? '成功' : '失败';
          layer.msg('订单信息修改' + result + '!');
          hideLayout($('#edit-order-layout'));
          loadOrder();
        });
      }
    });
  });
}

$('input[name=goods]').click(() => {
  let display = $('ul.goods').css('display');
  if (display === 'block')
    $('.goods').fadeOut();
  else
    $('.goods').fadeIn();
}).bind('input', function () {
  $.get('/goods/findAllGoodsByName', {name: $(this).val()}, names => {
    let liHtml = '';
    if (names.length === 0)
      liHtml = '<li onclick="writeGoodsName()">无数据</li>';
    else
      $.each(names, (i, v) => {
        liHtml += '<li onclick="writeGoodsName($(this))">' + v + '</li>';
      });
    $('.goods').html(liHtml);
  });
});

function writeGoodsName(elem) {
  if (elem !== undefined) $('#goods').val(elem.text());
  $('.goods').fadeOut();
}

function resetForm() {
  layui.use('form', () => {
    layui.form.render();
  })
}